import type { ValuesType, AssetLampPostStateType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type { shareEnum } from '~/store/base/typings'
import { defineComponent, ref, reactive, onMounted } from 'vue'
import { useStore } from 'vuex'
import {
  ElCard,
  ElFormItem,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElButton,
  ElIcon,
  ElInput,
  ElMessage,
  ElMessageBox
} from 'element-plus'
import { Plus, Delete, EditPen } from '@element-plus/icons-vue'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import AssetLampPostOptions from './option'
import styles from '~/pages/assetManagement/index.module.scss'
import ExportExcel from '~/components/ExportExcel'
import ImportExcel from './ImportExcel'
import { isURL } from '~/utils/validate'

export default defineComponent(function BasestationManage() {
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<ValuesType>({})
  const state = reactive<AssetLampPostStateType>({
    importVisible: false, // 导入 弹窗是否显示
    exportVisible: false, // 导出 弹窗是否显示
    modalVisible: false, // 新增/编辑 弹窗是否显示
    type: 'read',
    record: {}
  })
  const userState = useVuexGetters('user', ['permission']) // 按钮权限
  const baseState = useVuexGetters('base', [
    'baseStatusOpt',
    'operatorOpt',
    'shareOpt',
    'regionNameOpt'
  ])
  const store = useStore()
  const columns: TableColumnProps<ValuesType>[] = [
    {
      label: '基站名称',
      prop: 'name',
      showOverflowTooltip: true,
      minWidth: 200,
      fixed: 'left',
      unFixed: true,
      sortable: true, //  排序
      disabled: true //  不可编辑
    },
    {
      label: '所属区分',
      prop: 'workAreaName',
      minWidth: 160,
      sortable: true
    },
    {
      label: '所属地区',
      prop: 'regionName',
      showOverflowTooltip: true,
      minWidth: 220,
      sortable: true
    },
    {
      label: '基站状态',
      prop: 'isDeliverName',
      minWidth: 140,
      sortable: true
    },
    {
      label: '运营商',
      prop: 'infoServerName',
      minWidth: 220,
      sortable: true
    },
    {
      label: '查看全景',
      prop: 'overallView',
      width: 88,
      sortable: false,
      render: ({ row }) => (
        <>
          {isURL(row.overallView) ? (
            <a href={row.overallView} target="_blank" style="cursor: pointer; color: blue;">
              查看全景
            </a>
          ) : (
            '-'
          )}
        </>
      )
    },
    {
      label: '铁塔高度（米）',
      prop: 'height',
      minWidth: 160,
      sortable: true
    },
    {
      label: '是否共享',
      prop: 'shareName',
      minWidth: 160,
      align: 'center',
      sortable: true
    },
    {
      label: '基站类型',
      prop: 'baseType',
      minWidth: 160,
      sortable: true
    },
    {
      label: '建设类型',
      prop: 'buildType',
      minWidth: 160,
      sortable: true
      // render: (_, value) => {
      //   return <>{value === 2 ? '发现缺陷' : '正常'}</>
      // }
    },
    {
      label: '铁塔类型',
      prop: 'pagodaType',
      showOverflowTooltip: true,
      minWidth: 160,
      sortable: true
    },
    {
      label: '基站编号',
      prop: 'code',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '投运日期',
      prop: 'deliverDate',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '经度',
      prop: 'lon',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '纬度',
      prop: 'lat',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '详细地址',
      prop: 'address',
      showOverflowTooltip: true,
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '基站配置',
      prop: 'stationConfig',
      showOverflowTooltip: true,
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '机房类型',
      prop: 'machineType',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '配套类型',
      prop: 'stationType',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '风压-其它',
      prop: 'windConfig',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '接电类型',
      prop: 'powerConfig',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '备注',
      prop: 'memo',
      showOverflowTooltip: true,
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 160,
      sortable: true,
      hidden: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 160,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true, //  不可编辑
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('station_basestation_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <ElIcon>
                <EditPen />
              </ElIcon>
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('station_basestation_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <ElIcon>
                <Delete />
              </ElIcon>
              &nbsp;删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]

  onMounted(async () => {
    //  基站状态
    store.dispatch('base/BaseStatusGet', { code: 'asset_station_isdeliver' })
    //  运营商
    store.dispatch('base/OperatorGet', { code: 'asset_station_infoserver' })
    //  是否共享
    store.dispatch('base/ShareGet', { code: 'asset_station_share' })
  })

  // 新增/编辑
  const handleChangeOptionsModal = (type: AssetLampPostStateType['type'], record?: ValuesType) => {
    state.modalVisible = !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible && type !== 'read') proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  const handleDeleteSelectedData = async (params: string) => {
    await store
      .dispatch('base/GetBasestationRemove', {
        ids: params
      })
      .then((res) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: ValuesType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(() => {
        handleDeleteSelectedData(params)
      })
      .catch(() => {})
  }

  // 导入
  const handleChangeImportModal = () => {
    state.importVisible = !state.importVisible
    proSaasTableRef.value?.toSearch() // 刷新
  }

  // 导出
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  //  地区名称
  const remoteMethod = (query: string) => {
    if (query) {
      store.dispatch('base/BasestationGetAreaName', { name: query })
    }
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }

  return () => {
    if (state.modalVisible) {
      return (
        <AssetLampPostOptions
          record={state.record}
          type={state.type}
          cancel={() => handleChangeOptionsModal('add')}
        />
      )
    }

    return (
      <ElCard>
        <ProSaasTable<ValuesType>
          tableId="baseData"
          ref={proSaasTableRef}
          rowKey="id"
          hasSelection
          columns={columns}
          searchFormProps={{
            model: formValues
          }}
          dispatchType="base/GetBasestationList"
          headerTitle={
            <>
              {userState.permission.value.has('station_basestation_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {userState.permission.value.has('station_basestation_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
              {userState.permission.value.has('station_basestation_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <ElIcon>
                    <Delete />
                  </ElIcon>
                  &nbsp; 删除
                </ElButton>
              )}
              {userState.permission.value.has('station_basestation_import') && (
                <ElButton type="primary" onClick={() => handleChangeImportModal()}>
                  <AliIcon type="icon-daoru" />
                  &nbsp; 导入
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="name" prop="name" label="">
              <ElInput
                v-model={formValues.name}
                {...{ maxlength: 30 }}
                placeholder="请输入基站名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="areaKeyword" prop="areaKeyword" label="">
              <ElSelect
                v-model={formValues.areaKeyword}
                clearable
                filterable
                remote
                reserve-keyword
                remote-method={remoteMethod}
                onChange={clearSearchTable}
                placeholder="请输入地区名称"
              >
                {baseState.regionNameOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictValue} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="isDeliver" prop="isDeliver" label="">
              <ElSelect
                v-model={formValues.isDeliver}
                clearable
                onChange={clearSearchTable}
                placeholder="请选择基站状态"
              >
                {baseState.baseStatusOpt?.value?.map(
                  (item: shareEnum) =>
                    item.dictValue !== '规划中' && (
                      <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                    )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="infoServer" prop="infoServer" label="">
              <ElSelect
                v-model={formValues.infoServer}
                clearable
                onChange={clearSearchTable}
                placeholder="请选择运营商"
              >
                {baseState.operatorOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="share" prop="share" label="">
              <ElSelect
                v-model={formValues.share}
                clearable
                onChange={clearSearchTable}
                placeholder="是否共享"
              >
                {baseState.shareOpt?.value?.map((item: shareEnum) => (
                  <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="height" prop="height" label="">
              <ElInput
                v-model={formValues.height}
                {...{ maxlength: 30 }}
                placeholder="请输入塔高"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="baseType" prop="baseType" label="">
              <ElInput
                v-model={formValues.baseType}
                {...{ maxlength: 30 }}
                placeholder="请输入基站类型"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="buildType" prop="buildType" label="">
              <ElInput
                v-model={formValues.buildType}
                {...{ maxlength: 30 }}
                placeholder="请输入建设类型"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="pagodaType" prop="pagodaType" label="">
              <ElInput
                v-model={formValues.pagodaType}
                {...{ maxlength: 30 }}
                placeholder="请输入铁塔类型"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>
          ]}
        ></ProSaasTable>
        {/* 导出 */}
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="base/DasestationExport"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            exportNumber={proSaasTableRef.value?.pagination.total}
            onCancel={handleChangeExportModal}
          />
        )}

        {/* 导入 */}
        {state.importVisible && <ImportExcel doCancel={handleChangeImportModal} />}
      </ElCard>
    )
  }
})
